<template>
    <div ref="stickyRef" class="sticky">
        <slot></slot>
    </div>
</template>

<script lang="ts" setup>
import { nextTick, ref, watch } from 'vue'
import useScroll from '@/hooks/useScroll'

const props = defineProps({
    top: {
        type: Number,
        default: 53
    }
})

// css变量
const top = props.top + 'px'

// 通知吸顶
const emits = defineEmits<{
    (e: 'stickyChange', val: boolean): void
}>()

// 监听滚动
const stickyRef = ref()
const  { scrollTop } = useScroll()
const isSticky = ref<boolean>(false)
watch(scrollTop, val => {
    nextTick(() => {
        const rect = stickyRef.value.getBoundingClientRect()
        const result = rect.top <= props.top
        // 防止频繁通知
        if(result !== isSticky.value) {
            emits('stickyChange', result)
            isSticky.value = result
        }
    })
})

</script>

<style lang="less" scoped>
.sticky {
    position: sticky;
    top: v-bind(top);
    z-index: 998;
}
</style>